<?php

class Router {

	private $registry;
	private $path;
	private $args = array();

	public $file;
	public $controller;
	public $action;
	public $ids = null;

	function __construct($registry) {
		$this->registry = $registry;
	}

	function setPath($path) {

		if (is_dir($path) == false)	{
			throw new Exception ('Invalid controller path: `' . $path . '`');
		}

		$this->path = $path;
	}

	public function loader() {

		$this->getController();
		$entidad = LcznBD::infoEntidad($this->controller);

		if (!is_null($this->ids)) {
			$valores = explode(',',$this->ids);
			$entidad["claves"] = array_combine(array_keys($entidad["claves"]), $valores);
		}
		
		$this->registry->entidad = $entidad;

		if (file_exists($this->file)) {
			include $this->file;
			$class = $this->controller . 'Controller';
			$controller = new $class($this->registry);
		} else {
			$controller = new LcznController($this->registry);
		}

		if (is_callable(array($controller, $this->action)) == false) {
			$action = 'index';
		} else {
			$action = $this->action;
		}
		
		$controller->$action();
		$render = new LcznRender($this->registry);
		$render->edicion();
	}

	private function getController() {
		global $parametros;

		$route = (empty($_GET['qrystr'])) ? '' : $_GET['qrystr'];

		if (empty($route)) {
			$route = 'index';
		} else {
			$parts = explode('/', $route);
			
			$aux = explode('-',$parts[count($parts)-1]);
			
			switch(count($aux)) {
				case 3:
					$this->ids = $aux[2];
				case 2:
					$this->action = $aux[1];
				case 1:
					$this->controller = $aux[0];
					break;
			}
		}
	
		if (empty($this->controller)) {
			$this->controller = 'index';
		}

		if (empty($this->action)) {
			$this->action = 'index';
		}

		$this->file = $this->path .'/'. ucfirst($this->controller) . 'Controller.php';
	}
}

?>
